<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Link;
use App\Models\Linktag;

class LinkController extends Controller
{
    public function __construct()
    {
        $this->middleware('grant:link');
    }

    /**
     * 进入链接列表
     */
    public function getIndex()
    {
        $rows = Link::orderBy('id', 'ASC')->paginate(12);
        $data['links'] = $rows;
        $rows = Linktag::all();
        $data['tags'] = $rows;
        return view('admin/link/link_list', $data);
    }

    /**
     * 进入添加链接页面
     */
    public function getAdd()
    {
        $rows = Linktag::orderBy('id', 'ASC')->get();
        return view('admin/link/link_add')->withTags($rows);
    }

    /**
     * 进入编辑页面
     */
    public function getEdit($id = 0)
    {
        $link = Link::find($id);
        if (empty($link)) {
            return $this->warning('无效的链接');
        }
        $data['tag_ids'] = $link->tags->map(function ($tag) {
            return $tag->id;
        });
        $data['link'] = $link;
        $data['tags'] = Linktag::orderBy('id', 'ASC')->get();
        return view('admin/link/link_edit', $data);
    }

    /**
     * 进入标签列表页面
     */
    public function getTagList()
    {
        $rows = Linktag::orderBy('id', 'ASC')->get();
        return view('admin/link/taglist')->withTags($rows);
    }

}
